<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    /**
     * @var Request Request 实例
     */
    protected $request;

    /**
     * 默认响应输出类型,支持json/xml
     * @var string
     */
    protected $responseType = 'json';

    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {
        $this->request = is_null($request) ? Request::instance() : $request;

        //跨域请求检测
        check_cors_request();

        //移除HTML标签
//        $this->request->filter('trim,strip_tags,htmlspecialchars');
    }

    /**
     * 操作失败返回的数据
     * @param string $msg    提示信息
     * @param int    $code   错误码，默认为0
     * @param mixed  $data   要返回的数据
     * @param array  $header 发送的 Header 信息
     */
    protected function error($msg = '', $code = 0, $data = null, array $header = [])
    {
        $this->result($msg, $data, $code, $header);
    }

    /**
     * 操作成功返回的数据
     * @param string $msg    提示信息
     * @param int    $code   错误码，默认为1
     * @param mixed  $data   要返回的数据
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function success($data = null, $code = 1, $msg = 'ok', array $header = [])
    {
        $this->result($msg, $data, $code, $header);
    }


    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed  $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为0
     * @param array  $header 发送的 Header 信息
     * @return void
     */
    protected function result($msg, $data = null, $code = 0, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => $_SERVER['REQUEST_TIME'],
            'data' => $data,
        ];

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = response()->json($result, $code, $header);
        throw new HttpResponseException($response);
    }
}
